//
//  ZOAuthViewController.m
//  OC-weibo
//
//  Created by zero on 17/3/23.
//  Copyright © 2017年 zero. All rights reserved.
//

#import "ZOAuthViewController.h"
#import "ZUserAccountViewModel.h"


@interface ZOAuthViewController () <UIWebViewDelegate>

@property (nonatomic,weak)UIWebView *webView;
@end

@implementation ZOAuthViewController

#pragma mark
#pragma mark - 替换根视图
- (void)loadView{
    
    self.view = [[UIWebView alloc] init];
    
    self.webView = (UIWebView *)self.view;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.webView.opaque = false;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem initWithTitle:@"返回" andImageName:nil andTarget:self andSel:@selector(back)];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem initWithTitle:@"走火们" andImageName:nil andTarget:self andSel:@selector(jsonData)];
    
    self.webView.delegate = self;
    //  加载数据
    [self loadData];
}

#pragma mark
#pragma mark - 请求数据
- (void)loadData{
    
    NSString *urlString = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",app_Key,redirect_Uri];
    
    NSURL *url = [NSURL URLWithString:urlString];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [self.webView loadRequest:request];

}
#pragma mark
#pragma mark - back
- (void)back{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark
#pragma mark - json数据注入
- (void)jsonData{
    
    NSString *jsonString = @"document.getElementById('userId').value = '18875015218',document.getElementById('passwd').value = 'jllJLL940424'";
    
    [self.webView stringByEvaluatingJavaScriptFromString:jsonString];
}

#pragma mark
#pragma mark - webView的代理方法
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    NSLog(@"开始解析");
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"解析完成");
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString *flag = @"http://www.baidu.com/?code=";
    
    NSString *urlString = [[request URL] absoluteString];
    
    NSString *code = nil;
    if ([urlString containsString:flag]) {
        
        code = [urlString substringFromIndex:flag.length];
        
        //  获取token
        
        [[ZUserAccountViewModel shareUserAccountViewModel] getToken:code finishBlock:^(BOOL res) {
            
            if (res) {
                
                [[NSNotificationCenter defaultCenter] postNotificationName:ChangeVC object:@(VCTypeWelcomeViewController)];
                
            }else{
                NSLog(@"请求失败");
            }
        }];
        
        
        return NO;
    }
    
    return YES;
}


@end

